<template>
  <div style="height: 100%; margin: 10px">
    <div style="display: flex; margin-bottom: 10px; flex-direction: row; justify-content: flex-end">
      <a-upload
        v-if="store.getParent.id === 0"
        name="file"
        :action="uploadUrl"
        :showUploadList="false"
        @change="handleChange"
      >
        <a-button style="margin-right: 5px"> 导入环境 </a-button>
      </a-upload>
      <a-button type="primary" @click="handleCreate">{{ buttonText() }}</a-button>
    </div>
    <div style="margin-top: 10px">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="false"
        :row-key="(record) => record.moduleId"
        :row-selection="showRowSelection ? rowSelection : null"
        :loading="loading"
        size="middle"
        bordered
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <a @click="gotoModule(record)">{{ record.name }}</a>
          </template>
          <template v-else-if="column.key === 'operation'">
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a style="color: red" @click="handleDelete(record)">删除</a>
          </template>
          <template v-else-if="column.key === 'activeState'">
            <span :class="activeClass(record.activeState)">{{ record.activeState }}</span>
          </template>
          <template v-else-if="column.key === 'dependState'">
            <span :class="dependClass(record.dependState)">{{
              dependText(record.dependState)
            }}</span>
          </template>
          <template v-else-if="column.key === 'dependCount'">
            <a @click="hanldeDependCount(record)">{{ record.dependCount }}</a>
          </template>
        </template>
      </a-table>
      <div style="margin-top: 8px; display: flex; justify-content: space-between">
        <div>
          <a-dropdown v-if="showBatchOperation">
            <template #overlay>
              <a-menu @click="handleMenuClick">
                <a-menu-item key="1">
                  <UserOutlined />
                  设置上级
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              批量操作
              <DownOutlined />
            </a-button>
          </a-dropdown>
        </div>
        <div style="margin-left: auto">
          <a-pagination
            :current="currentPage"
            :page-size="pageSize"
            :total="total"
            :show-total="(total) => `总数 ${total}`"
            responsive
            show-size-changer
            show-less-items
            @change="onPageChange"
            @show-size-change="onShowSizeChange"
          />
        </div>
      </div>
    </div>

    <div v-if="showCreate">
      <ModuleCreateModal
        :title="createTitle()"
        :visible="showCreate"
        @ok="onCreateOk"
        @cancel="onCreateCancel"
      />
    </div>

    <div v-if="showEdit">
      <ModuleEditModal
        :title="editTitle()"
        :visible="showEdit"
        :module-data="moduleData"
        @ok="onEditOk"
        @cancel="onEditCancel"
      />
    </div>

    <div v-if="showDelete">
      <DeleteModal
        :visible="showDelete"
        :title="deleteTitle()"
        :data="deleteItem"
        @ok="onDeleteOk"
        @cancel="onDeleteCancel"
      />
    </div>

    <div v-if="showBatchEdit">
      <ModuleBatchEditModal
        :visible="showBatchEdit"
        title="批量设置上级"
        @ok="onBatchEditOk"
        @cancel="onBatchEditCancel"
      />
    </div>

    <div v-if="showDepend">
      <ModuleDependModal
        :visible="showDepend"
        :module-id="dependModuleId"
        title="模块依赖"
        @ok="onDependOk"
        @cancel="onDependCancel"
      />
    </div>
  </div>
</template>

<script lang="js">
  import {
    Button,
    Divider,
    Table,
    message,
    Pagination,
    Upload,
    Dropdown,
    Menu,
    MenuItem,
  } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  import bus from 'vue3-eventbus';
  import DeleteModal from '../components/DeleteModal.vue';
  import ModuleCreateModal from './ModuleCreateModal.vue';
  import ModuleEditModal from './ModuleEditModal.vue'
  import ModuleBatchEditModal from './ModuleBatchEditModal.vue'
  import ModuleDependModal from './ModuleDependModal.vue'
  import {
    createModule,
    deleteModule,
    editModule,
    getChildren,
    batchEditModule,
  } from '/@/api/module/module';
  import { useModuleStoreWithOut } from '/@/store/modules/module';
  import { UserOutlined, DownOutlined } from '@ant-design/icons-vue';

  export default {
    components: {
    "a-table": Table,
    "a-divider": Divider,
    "a-button": Button,
    "a-pagination": Pagination,
    "a-upload": Upload,
    "a-dropdown": Dropdown,
    "a-menu": Menu,
    "a-menu-item": MenuItem,
    ModuleCreateModal,
    ModuleEditModal,
    ModuleBatchEditModal,
    DeleteModal,
    UserOutlined,
    DownOutlined,
    ModuleDependModal,
    },
    data() {
      return {
        router: useRouter(),
        store: useModuleStoreWithOut(),
        uploadUrl: import.meta.env.VITE_GLOB_API_URL + "/module/import",
        showDepend: false,
        dependModuleId: 0,
        showDelete: false,
        deleteItem: null,
        showCreate: false,
        showEdit: false,
        showBatchEdit: false,
        moduleData: null,
        showRowSelection: false,
        rowSelection: {
          selectedRowKeys: [],
          onChange: this.onSelectChange,
        },
        loading: false,
        tableData: [],
        totalData: [],
        currentPage: 1,
        pageSize: 10,
        total: 10,
        columns: [
          {
            title: 'ID',
            key: 'moduleId',
            dataIndex: 'moduleId',
            align: 'center',
          },
          {
            title: 'Name',
            key: 'name',
            dataIndex: 'name',
            align: 'center',
          },
          {
            title: 'Description',
            key: 'desc',
            dataIndex: 'desc',
            align: 'center',
          },
          {
            title: 'Create Type',
            key: 'createType',
            dataIndex: 'createType',
            align: 'center',
          },
          {
            title: 'Module Type',
            key: 'moduleType',
            dataIndex: 'moduleType',
            align: 'center',
          },
          {
            title: 'Active State',
            key: 'activeState',
            dataIndex: 'activeState',
            align: 'center',
          },
          {
            title: 'Depend State',
            key: 'dependState',
            dataIndex: 'dependState',
            align: 'center',
          },
          {
            title: 'Depend Count',
            key: 'dependCount',
            dataIndex: 'dependCount',
            align: 'center',
          },
          {
            title: 'Create Time',
            key: 'createTime',
            dataIndex: 'createTime',
            align: 'center',
          },
          {
            title: 'Update Time',
            key: 'updateTime',
            dataIndex: 'updateTime',
            align: 'center',
          },
          {
            title: 'Operation',
            key: 'operation',
            dataIndex: 'operation',
            align: 'center',
            fixed: 'right',
            width: 120,
          },
        ],
      }
    },
    computed: {
      showBatchOperation() {
        return this.rowSelection.selectedRowKeys.length > 0
      },
    },
    watch: {
      'store.parent': {
        async handler() {
          console.log('store.parent changed:', this.store.getParent)
          await this.refreshTableData()
        }
      }
    },
    created () {
      if (this.store.getRoot.id === 0 || this.store.getRoot.name === 'none') {
        this.router.push("/module/index")
      }
    },
    async mounted() {
      this.refreshTableData()
      this.showRowSelection = (this.store.getParent.id !== 0)
    },
    methods: {
      // 根据当前页码和每页显示数量计算当前页数据
      updateTableData() {
        if (this.totalData != null) {
          const start = (this.currentPage - 1) * this.pageSize;
          const end = start + this.pageSize;
          this.tableData = this.totalData.slice(start, end);
        } else {
          this.tableData = []
        }
      },
      async refreshTableData() {
        this.totalData = (await getChildren({ parent: this.store.getParent.id }))
        this.total = this.totalData && this.totalData.length
        this.updateTableData()
      },
      activeClass(state) {
        return state === 'active' ? 'active' : 'inactive'
      },
      dependClass(state) {
        if (state === 0) {
          return 'depend-normal'
        } else if (state === 1) {
          return 'depend-fatal'
        } else if (state === 2) {
          return 'depend-warn'
        }
      },
      dependText(state) {
        if (state === 0) {
          return '正常'
        } else if (state === 1) {
          return '连接异常'
        } else if (state === 2) {
          return '业务异常'
        }
      },
      buttonText() {
        return this.store.getParent.name === 'none' ? "创建环境" : "创建模块"
      },
      deleteTitle() {
        return this.store.getParent.name === 'none' ? "删除环境" : "删除模块"
      },
      createTitle() {
        return this.store.getParent.name === 'none' ? "创建环境" : "创建模块"
      },
      editTitle() {
        return this.store.getParent.name === 'none' ? "编辑环境" : "编辑模块"
      },
      gotoModule(record) {
        if (record.parentName === 'none') {
          this.store.setRoot({
            id: record.moduleId,
            name: record.name,
            desc: record.desc,
            app: record.app,
            space: record.space,
            type: record.moduleType,
            parent: record.parentId,
          })
        }

        this.store.setParent({
          id: record.moduleId,
          name: record.name,
          desc: record.desc,
          app: record.app,
          space: record.space,
          type: record.moduleType,
          parent: record.parentId,
        })
        this.router.push('/module/' + record.name)
      },
      async refreshTable() {
        this.refreshTableData()
        this.rowSelection.selectedRowKeys = []
        bus.emit('refreshTree')
      },
      handleCreate() {
        this.showCreate = true
      },
      onCreateOk(data) {
        this.showCreate = false
        createModule({
          name: data.name,
          desc: data.desc,
          parent: data.parentId,
          createType: data.createType,
          moduleType: data.moduleType,
          app: data.app,
          space: data.space,
          children: data.children,
        }).then(async () => {
          message.success("create module success")
          this.refreshTable()
          bus.emit("createModule")
        }).catch(() => {
          message.error("create module failed")
        })
      },
      onCreateCancel() {
        this.showCreate = false
      },
      handleEdit(record) {
        this.moduleData = record
        this.showEdit = true
      },
      onEditOk(data) {
        this.showEdit = false
        editModule({
          id: data.id,
          name: data.name,
          desc: data.desc,
          parent: data.parentId,
        }).then(async () => {
          message.success("edit module success")
          this.refreshTable()
          bus.emit("editModule")
        }).catch(() => {
          message.error("edit module failed")
        })
      },
      onEditCancel() {
        this.showEdit = false
      },
      handleDelete(record) {
        this.deleteItem = record
        this.showDelete = true
      },
      onDeleteOk(item) {
        this.showDelete = false
        deleteModule({
          id: item.moduleId
        }).then(async () => {
          this.refreshTable()
          message.success('delete module success');
        }).catch(() => {
          message.error('delete module failed');
        })
      },
      onDeleteCancel() {
        this.showDelete = false
      },
      async onShowSizeChange(current, size) {
        this.pageSize = size
        this.currentPage = 1
        this.updateTableData()
      },
      onPageChange(page) {
        this.currentPage = page
        this.updateTableData()
      },
      onSelectChange(selectedRowKeys) {
        this.rowSelection.selectedRowKeys = selectedRowKeys
      },
      handleBatchEdit() {
        this.showBatchEdit = true
      },
      onBatchEditOk(data) {
        this.showBatchEdit = false
        batchEditModule({
          modules: this.rowSelection.selectedRowKeys,
          parent: data.parentId,
        }).then(() => {
          message.success("batch edit modules success")
          this.refreshTable()
          bus.emit("editModule")
        }).catch((e) => {
          message.error("batch edit modules failed")
          console.error("batch edit modules failed", e)
        })
      },
      onBatchEditCancel() {
        this.showBatchEdit = false
      },
      handleChange(info) {
        console.log("handleChange:", info)
        if (info.file.status === "uploading") {
          this.loading = true
        } else if (info.file.status === "done") {
          this.loading = false
          this.refreshTableData()
          message.success("import success")
        } else {
          message.error("import failed")
          this.loading = false
        }
      },
      handleMenuClick(e) {
        if (e.key === "1") {
          this.handleBatchEdit()
        }
      },
      hanldeDependCount(record) {
        console.log(record)
        this.showDepend = true
        this.dependModuleId = record.moduleId
      },
      onDependCancel() {
        this.showDepend = false
      },
      onDependOk() {
        this.showDepend = false
      }
    },
  }
</script>

<style>
  .active {
    color: green;
  }
  .inactive {
    color: red;
  }
  .depend-normal {
    color: green;
  }
  .depend-warn {
    color: #f7b84b;
  }
  .depend-fatal {
    color: red;
  }
</style>
